﻿using System.IO.Compression;

namespace XinLife.Core.Helper
{
    /// <summary>
    /// ZIP 解压缩
    /// </summary>
    public sealed class ZipHelper
    {
        /// <summary>
        /// 多文件压缩成ZIP
        /// </summary>
        /// <param name="fileSources">源文件路径</param>
        /// <param name="fileOut">ZIP文件路径</param>
        /// <returns></returns>
        public static bool FilesZip(List<string> fileSources, string fileOut)
        {
            try
            {
                using FileStream zipFileToOpen = new(fileOut, FileMode.Create);
                using ZipArchive archive = new(zipFileToOpen, ZipArchiveMode.Create);
                foreach (var file in fileSources)
                {
                    if (File.Exists(file))
                    {
                        FileInfo fileInfo = new FileInfo(file);
                        string path = Path.Combine(Directory.GetCurrentDirectory(), "upload");
                        if (!fileInfo.FullName.Contains(path))
                        {
                            continue;
                        }
                    }

                    //计算相对路径
                    string fileName = Path.GetFileName(file);
                    ZipFile(file, fileName, archive);
                }
            }
            catch
            {
                return false;
            }
            return true;
        }

        private static void ZipFile(string fileSource, string fileName, ZipArchive archive)
        {
            var baseDirec = Directory.GetCurrentDirectory();
            fileSource = Path.Combine(baseDirec, fileSource).Replace("\\", "/");
            ZipArchiveEntry readMeEntry = archive.CreateEntry(fileName);
            readMeEntry.LastWriteTime = File.GetLastWriteTime(fileSource);
            using Stream stream = readMeEntry.Open();
            byte[] bytes = File.ReadAllBytes(fileSource);
            stream.Write(bytes);
        }
    }
}
